import axios from 'axios'

// 统一的 AI 客户端，兼容原有API并支持IMA增强功能
const ai = axios.create({
  baseURL: '/ai',
  timeout: 30000, // AI 操作可能较慢，延长超时
  headers: {
    'Content-Type': 'application/json'
  }
})

// AI 服务接口类型定义
export interface UploadDocResponse {
  ok: boolean
  chunks: number
  filename: string
  message: string
}

export interface AskRequest {
  question: string
  userId?: number
  courseId?: number
  topK?: number
  docIds?: string[]
  useAI?: boolean
}

export interface AskResponse {
  answer: string
  sources?: string[]
  source_docs?: string[]
}

export interface IntelligentQueryRequest {
  question: string
  userId?: number
  courseId?: number
  topK?: number
  useAI?: boolean
  queryMode?: 'precise' | 'creative' | 'hybrid'
  aiModel?: 'qwen' | 'openai' | 'deepseek' | 'auto'
  docIds?: string[]
}

export interface DocumentInfo {
  id: string
  filename: string
  file_type: string
  file_size: number
  chunk_count: number
}

export interface ListDocsResponse {
  ok: boolean
  documents: DocumentInfo[]
  count: number
}

export interface ClearDocsResponse {
  ok: boolean
  message: string
}

export const aiApi = {
  /**
   * 上传文档到 RAG 知识库
   */
  uploadDoc(file: File, userId?: string, courseId?: string): Promise<{ data: UploadDocResponse }> {
    const formData = new FormData()
    formData.append('file', file)
    if (userId) formData.append('userId', userId)
    if (courseId) formData.append('courseId', courseId)
    
    return ai.post('/docs/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },

  /**
   * 基于已上传文档进行问答
   */
  ask(payload: AskRequest): Promise<{ data: AskResponse }> {
    return ai.post('/ask', payload)
  },

  /**
   * 健康检查
   */
  health(): Promise<{ data: { ok: boolean } }> {
    return ai.get('/health')
  },

  /**
   * 列出文档库中的所有文档
   */
  listDocs(userId?: number, courseId?: number): Promise<{ data: ListDocsResponse }> {
    const params = new URLSearchParams()
    if (userId !== undefined && userId !== null) params.append('userId', String(userId))
    if (courseId !== undefined && courseId !== null) params.append('courseId', String(courseId))
    
    const queryString = params.toString()
    const url = queryString ? `/docs/list?${queryString}` : '/docs/list'
    console.log('📋 调用文档列表API:', url)
    
    return ai.get(url)
  },

  /**
   * 清空文档库
   */
  clearDocs(userId?: number, courseId?: number): Promise<{ data: ClearDocsResponse }> {
    const formData = new FormData()
    if (userId) formData.append('userId', String(userId))
    if (courseId) formData.append('courseId', String(courseId))
    
    return ai.post('/docs/clear', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },

  /**
   * 删除指定文档
   */
  deleteDoc(docId: string, userId?: number, courseId?: number): Promise<{ data: { ok: boolean; message: string; doc_id: string } }> {
    const params = new URLSearchParams()
    if (userId !== undefined && userId !== null) params.append('userId', String(userId))
    if (courseId !== undefined && courseId !== null) params.append('courseId', String(courseId))
    
    const queryString = params.toString()
    const url = queryString ? `/docs/${docId}?${queryString}` : `/docs/${docId}`
    
    return ai.delete(url)
  },

  /**
   * 强制清空所有文档库
   */
  forceClearAll(): Promise<{ data: ClearDocsResponse }> {
    return ai.post('/docs/force-clear')
  }
}